package cn.gson.crm.controller.permission;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.dao.RoleDao;
import cn.gson.crm.model.entity.BrandModel;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Role;
import cn.gson.crm.model.mapper.EmployeeMapper;

@Controller
@RequestMapping("employee")
public class EmployeeController {
	@Autowired
	EmployeeMapper empMapper;
	
	@Autowired
	EmployeeDao eDao;
	
	@Autowired
	RoleDao rDao;
	
	//保存Employee
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public JSONObject save(HttpServletRequest request, @Valid Employee employee,@Valid BrandModel brandModel, BindingResult br) throws IOException {
		System.out.println(employee.toString());
		JSONObject message = new JSONObject();
		//如果valid校验失败
		if(br.hasErrors()) {
			message.put("error", "校验失败");
		} else {
			//如果有选择角色，则进行更新
//			if(roleIds != null && roleIds.length > 0) {
//				List<Role> roles = new LinkedList<>();
//				for(Long rId : roleIds) {
//					roles.add(rDao.findOne(rId));
//				}
//				//employee.setRoles(roles);
//			}
			if(employee.getId() == null) {
				//新用户，进行密码加密
				employee.setPassword(DigestUtils.md2Hex(employee.getPassword()));
			} else {
				//旧用户，用数据库加密后的密码取代明文密码
				employee.setPassword(eDao.findOne(employee.getId()).getPassword());
			}
			if(employee.getLeader().getId() == null) employee.setLeader(null);
			System.out.println(brandModel.toString());
			//进行图片存储
			if(brandModel.getSourceFile()!=null && !brandModel.getSourceFile().isEmpty()) {
				ByteArrayInputStream byIntStream = new ByteArrayInputStream(brandModel.getSourceFile().getBytes());
				BufferedImage bufImg = ImageIO.read(byIntStream);
				SimpleDateFormat f=new SimpleDateFormat("yyyyMMddhhmmss");
				String fileName = f.format(new Date());
//				String prePath = request.getContextPath();
//				String path = prePath + "/src/main/webapp/images/employee_photo/" + fileName + ".jpg";
//				String path = "/crm/src/main/webapp/images/employee_photo/" + fileName + ".jpg";
//				String path = "images/employee_photo/" + fileName + ".jpg";
				String path = fileName + ".jpg";
				String fullPath = "C:/profiles/" +path;
				File file = new File(fullPath);
				if (!file.exists()) {
	                file.mkdirs();
	            } 
				ImageIO.write(bufImg, "jpg", file);
				employee.setPicture(path);
			}
			//进行保存
			System.out.println(employee.toString());
			eDao.save(employee);
			message.put("success", true);
		}
		return message;
	}
	

	//返回全部employee,分页
	@RequestMapping("list")
	@ResponseBody
	public Map<String, Object> list(@RequestParam(defaultValue = "1") int page,
			@RequestParam(defaultValue = "20") int rows) {
		PageRequest pr = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "id"));
		Page<Employee> members = eDao.findAll(pr);
		Map<String, Object> data = new HashMap<>();
		data.put("rows", members.getContent());
		data.put("total", members.getTotalElements());
		return data;
	}
	
	@RequestMapping({"simplelist","simplelist/{id}"})
	@ResponseBody
	public List<Employee> getSimpleList(@PathVariable(required = false) Long id){
		List<Employee> list = new LinkedList<>();
//		Iterable<Employee> es = id==null?eDao.findAll():eDao.findAllByIdNot(id);
		Iterable<Employee> es = eDao.findAll();
		for(Employee e : es)
			if(!e.getId().equals(id))
				list.add(e);
		return list;
	}
	
	//删除Employee
	@PostMapping("delete/{id}")
	@ResponseBody
	@Transactional
	public JSONObject delete(@PathVariable(required = true)  Long id) {
		eDao.delete(id);
		JSONObject result = new JSONObject();
		result.put("success", true);
		return result;
	}
	
	//检查电话是否存在
	@PostMapping({"exist/tel/{id}","exist/tel"})
	@ResponseBody
	public boolean isTelephoneExisting(String tel, @PathVariable(required = false) Long id) {
		if(id != null&& tel != null) {
			if(tel.equals(eDao.findOne(id).getTelephone())) return true;
		}
		return eDao.countByTelephone(tel) == 0;
	}
	
	//检查邮箱是否存在
	@PostMapping({"exist/email/{id}","exist/email"})
	@ResponseBody
	public boolean isEmailExisting(String email, @PathVariable(required = false) Long id) {
		if(id != null && email != null) {
			if(email.equals(eDao.findOne(id).getEmail())) return true;
		}
		return eDao.countByEmail(email) == 0;
	}
	
	//处理form显示请求
	@GetMapping({ "form", "form/{id}" })
	public String getEmployeeForm(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("e", eDao.findOne(id));
		}
		model.addAttribute("roles", rDao.findAllByEnable(true));
		return "permission/employee/form";
	}
	
//	@RequestMapping("get/{id}")
//	@ResponseBody
//	public Employee getEmployee(@PathVariable(required = true) Long id) {
//		System.out.println("gete!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
//		return eDao.findOne(id);
//	}
	
	//处理info显示请求
	@RequestMapping({"info/{id}" })
	public String getEmployeeInfo(@PathVariable(required = false) Long id, Model model) {
		if (id != null) {
			model.addAttribute("e", eDao.findOne(id));
		}
		return "permission/employee/info";
	}
	/**
	 * 查询所有未离职员工姓名
	 * @author hzl
	 * @return
	 */
	@RequestMapping("empNamelist")
	@ResponseBody
	public JSONArray getEmployee(){
		JSONArray jsonArray = new JSONArray(); 
		List<Employee> employeelist=eDao.findByState(true);
		for (Employee employee : employeelist) {
	        jsonArray.add(employee);  
		}
		return jsonArray;
	}

	
	
	
}
